<script setup>
import { ref, onMounted } from 'vue'
import { getHrInfoByIdApi } from '@/api/user.js'
import { getCompanyOpenJobListApi } from '@/api/position.js'

// 用户信息
const userInfo = ref({
  name: '',
  avatar: '/static/images/avatar.png',
  company: '',
  position: '',
  tags: [],
  signature: ''
})

// 公司信息
const companyInfo = ref({
  name: '',
  funding: '未融资',
  size: '20-99人',
  industry: '计算机软件'
})

// 职位列表数据
const positionList = ref([])
const loading = ref(false)
const loadingMore = ref(false)
const hasMore = ref(true)
const currentPage = ref(1)
const pageSize = ref(10)
const totalPages = ref(0)
const totals = ref(0)

// 页面参数
const hrId = ref('')
const companyId = ref('') // 公司ID，用于跳转企业主页

// 触摸事件处理 - 解决H5浏览器滚动问题
const touchStartX = ref(0);
const touchStartY = ref(0);

const onTagsTouchStart = (e) => {
  touchStartX.value = e.touches[0].clientX;
  touchStartY.value = e.touches[0].clientY;
};

const onTagsTouchMove = (e) => {
  const touchX = e.touches[0].clientX;
  const touchY = e.touches[0].clientY;
  const deltaX = touchX - touchStartX.value;
  const deltaY = touchY - touchStartY.value;
  
  // 如果是水平滑动，阻止默认行为
  if (Math.abs(deltaX) > Math.abs(deltaY)) {
    e.preventDefault();
  }
};

const onTagsTouchEnd = (e) => {
  // 触摸结束处理
};

// 鼠标滚轮事件 - 支持H5浏览器
const onTagsWheel = (e) => {
  e.preventDefault();
  const scrollView = e.currentTarget;
  if (scrollView) {
    scrollView.scrollLeft += e.deltaY;
  }
};

// 获取页面参数
const getPageParams = () => {
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  const options = currentPage.options || {};
  
  hrId.value = options.hrId || '';
  console.log('HR查看页面参数:', { hrId: hrId.value });
};

// 获取职位列表
const getPositionList = async (isRefresh = false) => {
  console.log('获取职位列表 - isRefresh:', isRefresh, 'currentPage:', currentPage.value)

  if (loading.value && !isRefresh) {
    console.log('正在加载中，跳过')
    return
  }
  if (loadingMore.value && isRefresh) {
    console.log('正在加载更多，跳过刷新')
    return
  }

  try {
    if (isRefresh) {
      currentPage.value = 1
      loading.value = true
      positionList.value = [] // 清空列表
      console.log('刷新模式 - 清空列表，重置页码')
    } else {
      if (!hasMore.value) {
        console.log('无更多数据可加载')
        return
      }
      loadingMore.value = true
      console.log('加载更多模式 - 页码:', currentPage.value)
    }

    const params = {
      pageNo: isRefresh ? 1 : currentPage.value,
      pageSize: pageSize.value,
      companyId: companyId.value || '',
    }

    console.log('请求参数:', params)
    const response = await getCompanyOpenJobListApi(params)
    console.log('职位列表响应:', response)

    if (response) {
      totalPages.value = response.totalPages || 0
      totals.value = response.totals || 0

      console.log(
        '响应数据 - totalPages:',
        totalPages.value,
        'totals:',
        totals.value,
        'list.length:',
        (response.list || []).length
      )

      if (isRefresh) {
        positionList.value = response.list || []
        currentPage.value = 1
        console.log('刷新完成 - 当前列表长度:', positionList.value.length)
      } else {
        positionList.value.push(...(response.list || []))
        console.log('加载更多完成 - 当前列表长度:', positionList.value.length)
      }

      // 判断是否还有更多数据
      hasMore.value = currentPage.value < totalPages.value
      console.log(
        '分页状态 - hasMore:',
        hasMore.value,
        'currentPage:',
        currentPage.value,
        'totalPages:',
        totalPages.value
      )
    } else {
      console.error('响应数据为空')
    }
  } catch (error) {
    console.error('获取职位列表失败:', error)
    // 静默失败，不显示错误提示
  } finally {
    loading.value = false
    loadingMore.value = false
    console.log(
      '请求结束 - loading:',
      loading.value,
      'loadingMore:',
      loadingMore.value
    )
  }
}

// 上拉加载更多
const onLoadMore = () => {
  console.log(
    '上拉加载更多 - currentPage:',
    currentPage.value,
    'totalPages:',
    totalPages.value
  )

  if (loadingMore.value || !hasMore.value) {
    console.log('已在加载中或无更多数据')
    return
  }

  const nextPage = currentPage.value + 1
  if (nextPage > totalPages.value) {
    console.log('已达最后一页')
    hasMore.value = false
    return
  }

  currentPage.value = nextPage
  getPositionList(false)
}

// 格式化薪资显示
const formatSalary = (job) => {
  if (job.beginSalary && job.endSalary && job.monthlySalary) {
    return `${job.beginSalary}-${job.endSalary}K·${job.monthlySalary}个月`
  }
  return '面议'
}

// 获取HR信息
const getHrInfo = async () => {
  if (!hrId.value) {
    uni.showToast({
      title: 'HR信息获取失败',
      icon: 'none'
    });
    return;
  }

  try {
    console.log('获取指定HR信息:', hrId.value);
    const response = await getHrInfoByIdApi(hrId.value);
    console.log('HR信息接口返回:', response)
    
    if (response) {
      const data = response
      
      // 处理显示名称
      let displayName = ''
      if (data.showWhichName === 1) {
        displayName = data.realName || '未知'
      } else if (data.showWhichName === 2) {
        displayName = data.nickName || data.realName || '未知'
      } else {
        displayName = data.realName || '未知'
      }
      
      // 处理标签
      let tags = []
      if (data.hrTags && data.hrTags.trim()) {
        try {
          // 如果标签是JSON字符串，尝试解析
          if (typeof data.hrTags === 'string') {
            // 先尝试JSON解析
            try {
              const parsedTags = JSON.parse(data.hrTags)
              if (Array.isArray(parsedTags)) {
                tags = parsedTags.filter(tag => tag && tag.trim())
              }
            } catch (e) {
              // JSON解析失败，按逗号分割
              tags = data.hrTags.split(',').filter(tag => tag && tag.trim())
            }
          } else if (Array.isArray(data.hrTags)) {
            tags = data.hrTags.filter(tag => tag && tag.trim())
          }
        } catch (e) {
          console.error('标签解析失败:', e)
          // 如果所有解析都失败，按逗号分割
          tags = data.hrTags.split(',').filter(tag => tag && tag.trim())
        }
      }
      
      // 更新用户信息
      userInfo.value = {
        name: displayName,
        avatar: data.face,
        company: data.companyName || '未知公司',
        position: data.position || '未知职位',
        tags: tags,
        signature: data.hrSignature || ''
      }
     
      // 保存公司ID，用于跳转企业主页
      companyId.value = data.companyId || '';
      
      // 更新公司信息
      companyInfo.value = {
        name: data.companyName || '未知公司',
        funding: '未融资',
        size: '20-99人',
        industry: '计算机软件'
      }
      
      // 获取职位列表
      if (companyId.value) {
        getPositionList(true)
      }
    }
  } catch (error) {
    console.error('获取HR信息失败:', error)
    uni.showToast({
      title: '获取信息失败',
      icon: 'none'
    })
  }
}

// 跳转到企业查看页面
const goToCompanyView = () => {
  if (!companyId.value) {
    uni.showToast({
      title: '企业信息获取失败',
      icon: 'none'
    });
    return;
  }
  
  uni.navigateTo({
    url: `/pages/candidate/position/companyView?companyId=${companyId.value}`
  });
};

// 跳转到职位详情
const goToPositionDetail = (position) => {
  console.log('跳转到职位详情，position:', position);
  const jobId = position.id || position.jobId; // 确保兼容性
  uni.navigateTo({
    url: `/pages/candidate/position/positionDetail?jobId=${jobId}`
  })
}

onMounted(() => {
  // 先获取页面参数，再获取HR信息
  getPageParams()
  getHrInfo()
  console.log('HR查看页面加载成功')
})

// 定义onShow生命周期函数
function onShow() {
  console.log('hrView页面onShow触发')
}
</script>
  
<template>
  <view class="my-home-container">
    <!-- 顶部返回按钮 -->
    <view class="header">
      <view class="back-btn" @tap="uni.navigateBack()">
        <image src="/static/icons/left_arrow.png" class="back-icon" />
      </view>
    </view>

    <!-- 背景图片区域 -->
    <view class="background-section">
      <image src="/static/images/hr_bg.jpg" class="bg-image" mode="aspectFill" />
    </view>

    <!-- 用户信息卡片 -->
    <view class="user-card">
      <!-- 头像 -->
      <view class="avatar-container">
        <image :src="userInfo.avatar" class="avatar" mode="aspectFill" />
      </view>
      
      <!-- 用户信息 -->
      <view class="user-info">
        <view class="user-details">
          <text class="user-name">{{ userInfo.name }}</text>
          <text class="company-position">{{ userInfo.company }} · {{ userInfo.position }}</text>
          
          <!-- 标签 -->
          <view class="tags-container">
            <view class="tags-wrapper">
              <view v-if="userInfo.tags && userInfo.tags.length > 0" class="tags-scroll-area">
                <scroll-view 
                  scroll-x="true" 
                  class="tags-scroll"
                  :scroll-with-animation="true"
                  :enhanced="true"
                  :bounces="false"
                  :show-scrollbar="false"
                  @touchstart="onTagsTouchStart"
                  @touchmove="onTagsTouchMove"
                  @touchend="onTagsTouchEnd"
                  @wheel="onTagsWheel"
                >
                  <view class="tags-content">
                    <view 
                      v-for="(tag, index) in userInfo.tags" 
                      :key="index"
                      class="tag"
                      :class="'tag-blue'"
                    >
                      {{ tag }}
                    </view>
                  </view>
                </scroll-view>
              </view>
              <view v-else class="no-tags-text">暂未设置</view>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 个性签名 -->
    <view class="signature-section">
      <text class="section-title">个性签名</text>
      <view class="signature-card">
        <view class="signature-container">
          <text class="signature-text">{{ userInfo.signature || '您还未设置个性签名~' }}</text>
        </view>
      </view>
    </view>

    <!-- 任职企业卡片 -->
    <view class="company-section">
      <text class="section-title">任职企业</text>
      
      <!-- 公司信息卡片 -->
      <view class="company-card" @tap="goToCompanyView">
        <view class="company-header">
          <view class="company-icon-container">
            <image src="/static/icons/company/company.png" class="company-icon" />
          </view>
          <view class="company-info">
            <text class="company-name">{{ companyInfo.name }}</text>
            <text class="company-details">{{ companyInfo.funding }}·{{ companyInfo.size }}·{{ companyInfo.industry }}</text>
          </view>
          <image src="/static/icons/right-arrow.png" class="arrow-icon" />
        </view>
      </view>
      
    </view>

    <!-- 发布职位区域 -->
    <view class="positions-section">
      <view class="positions-header">
        <view class="header-left">
          <text class="section-title">发布职位</text>
          <view class="position-count">{{ positionList.length }}</view>
        </view>
        <text class="dynamics-tab">动态</text>
      </view>
      
      <!-- 职位列表 -->
      <scroll-view 
        class="positions-scroll"
        scroll-y
        @scrolltolower="onLoadMore"
        lower-threshold="50"
        style="height: 400rpx;"
      >
        <!-- 加载中提示 -->
        <view v-if="loading && positionList.length === 0" class="loading-wrapper">
          <text class="loading-text">加载中...</text>
        </view>

        <!-- 职位列表 -->
        <view class="positions-list" v-else-if="positionList.length > 0">
          <view 
            class="position-item" 
            v-for="position in positionList" 
            :key="position.id"
            @tap="goToPositionDetail(position)"
          >
            <view class="position-header">
              <text class="position-title">{{ position.jobName }}</text>
              <text class="position-salary">{{ formatSalary(position) }}</text>
            </view>
            <view class="position-details">
              <text class="detail-item">{{ position.city }}</text>
              <text class="detail-item">{{ position.expYears }}</text>
              <text class="detail-item">{{ position.edu }}</text>
            </view>
          </view>
        </view>

        <!-- 空状态 -->
        <view class="empty-state" v-else-if="!loading">
          <text class="empty-text">暂无职位数据</text>
        </view>

        <!-- 加载更多 -->
        <view v-if="loadingMore" class="load-more">
          <text class="load-text">加载中...</text>
        </view>

        <!-- 已到底部 -->
        <view v-else-if="!hasMore && positionList.length > 0" class="no-more">
          <text class="no-more-text">已经到底了</text>
        </view>
      </scroll-view>
    </view>
  </view>
</template>
  
<style lang="scss" scoped>
.my-home-container {
  min-height: 100vh;
  background-color: #f9fafb;
  position: relative;
}

/* 顶部返回按钮 */
.header {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 100;
  padding: 20rpx;
  padding-top: 60rpx;
}

.back-btn {
  width: 60rpx;
  height: 60rpx;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  backdrop-filter: blur(10rpx);
}

.back-icon {
  width: 32rpx;
  height: 32rpx;
}

/* 背景图片区域 */
.background-section {
  height: 256rpx;
  overflow: hidden;
}

.bg-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

/* 用户信息卡片 */
.user-card {
  background: #ffffff;
  border-radius: 20rpx 20rpx 0 0;
  margin: -54rpx 16rpx 0;
  padding: 128rpx 48rpx 48rpx;
  position: relative;
  box-shadow: 0 8rpx 40rpx rgba(0, 0, 0, 0.1);
}

/* 头像容器 */
.avatar-container {
  position: absolute;
  top: -44rpx;
  left: 38rpx;
  width: 148rpx;
  height: 148rpx;
  border-radius: 50%;
  overflow: hidden;
  border: 10rpx solid #ffffff;
  background: #ffffff;
  box-shadow: 0 8rpx 40rpx rgba(0, 0, 0, 0.1);
}

.avatar {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

/* 用户信息 */
.user-info {
  display: flex;
  align-items: flex-start;
}

.user-details {
  width: 100%;
  flex: 1;
}

.user-name {
  font-size: 40rpx;
  font-weight: bold;
  color: #111827;
  display: block;
  margin-bottom: 8rpx;
}

.company-position {
  font-size: 28rpx;
  color: #6b7280;
  display: block;
  margin-bottom: 24rpx;
}

/* 标签 */
.tags-container {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  border-radius: 16rpx;
  margin-top: 16rpx;
  min-height: 80rpx; /* 确保容器有足够高度 */
}

.tags-wrapper {
  display: flex;
  flex: 1;
  align-items: center;
  min-width: 0; /* 防止flex子元素溢出 */
}

.tags-scroll-area {
  flex: 1;
  min-width: 0;
}

.tags-scroll {
  width: 100%;
  overflow: hidden;
  white-space: nowrap;
  align-self: center;
  /* H5浏览器兼容性增强 */
  -webkit-overflow-scrolling: touch;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
  /* 确保在H5中可滚动 */
  position: relative;
  z-index: 1;
}

.tags-content {
  display: flex;
  gap: 16rpx;
  padding: 8rpx 0;
  min-width: max-content;
}

.tag {
  display: inline-flex;
  align-items: center;
  padding: 8rpx 24rpx;
  border-radius: 9999rpx;
  font-size: 28rpx;
  white-space: nowrap;
  flex-shrink: 0;
  max-width: 200rpx; /* 限制标签最大宽度 */
  overflow: hidden;
  text-overflow: ellipsis;
  margin-right: 16rpx;
  box-sizing: border-box;
}

.tag-blue {
  background: #dbeafe;
  color: #2563eb;
}

.tag-green {
  background: #dcfce7;
  color: #16a34a;
}

.no-tags-text {
  font-size: 28rpx;
  color: #9ca3af;
  font-style: italic;
}

/* 个性签名区域 */
.signature-section {
  padding: 48rpx 32rpx 0;
}

.signature-card {
  background: #ffffff;
  border-radius: 24rpx;
  padding: 32rpx;
  box-shadow: 0 2rpx 20rpx rgba(0, 0, 0, 0.05);
}

.signature-container {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  border-radius: 16rpx;
  padding: 20rpx 24rpx;
}

.signature-text {
  font-size: 28rpx;
  color: #6b7280;
  flex: 1;
}

/* 任职企业区域 */
.company-section {
  padding: 48rpx 32rpx;
}

.section-title {
  font-size: 36rpx;
  font-weight: 600;
  color: #111827;
  margin-bottom: 32rpx;
  display: block;
}

.company-card,
.view-positions-card {
  background: #ffffff;
  border-radius: 24rpx;
  padding: 32rpx;
  margin-bottom: 32rpx;
  box-shadow: 0 2rpx 20rpx rgba(0, 0, 0, 0.05);
}

.company-header {
  display: flex;
  align-items: center;
}

.company-icon-container,
.view-icon-container {
  width: 96rpx;
  height: 96rpx;
  border-radius: 16rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 24rpx;
}

.company-icon-container {
  background: #f3f4f6;
}

.view-icon-container {
  background: #ccfbf1;
}

.company-icon {
  width: 48rpx;
  height: 48rpx;
}

.view-icon {
  width: 48rpx;
  height: 48rpx;
}

.company-info {
  flex: 1;
}

.company-name {
  font-size: 32rpx;
  font-weight: 500;
  color: #111827;
  display: block;
  margin-bottom: 8rpx;
}

.company-details {
  font-size: 28rpx;
  color: #6b7280;
  display: block;
}

.view-text {
  font-size: 32rpx;
  font-weight: 500;
  color: #0d9488;
  display: block;
}

.arrow-icon {
  width: 32rpx;
  height: 32rpx;
}

/* 发布职位区域 */
.positions-section {
  padding: 0 32rpx 48rpx;
}

.positions-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 32rpx;
}

.header-left {
  display: flex;
  align-items: center;
}

.position-count {
  background: #f3f4f6;
  color: #6b7280;
  font-size: 28rpx;
  padding: 8rpx 16rpx;
  border-radius: 9999rpx;
  margin: 0 16rpx;
}

.dynamics-tab {
  color: #6b7280;
  font-size: 32rpx;
  margin-left: auto;
}

/* 职位滚动容器 */
.positions-scroll {
  width: 100%;
  box-sizing: border-box;
}

/* 职位列表 */
.positions-list {
  display: flex;
  flex-direction: column;
  gap: 32rpx;
  padding: 20rpx;
}

.position-item {
  background: #ffffff;
  border-radius: 24rpx;
  padding: 32rpx;
  box-shadow: 0 2rpx 20rpx rgba(0, 0, 0, 0.05);
}

.position-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 16rpx;
}

.position-title {
  font-size: 32rpx;
  font-weight: 500;
  color: #111827;
  flex: 1;
}

.position-salary {
  font-size: 32rpx;
  font-weight: 600;
  color: #0d9488;
}

.position-details {
  display: flex;
  flex-wrap: wrap;
  gap: 16rpx;
}

.detail-item {
  font-size: 28rpx;
  color: #6b7280;
}

/* 响应式设计 */
@media (max-width: 750rpx) {
  .user-card {
    margin: -64rpx 24rpx 0;
    padding: 128rpx 32rpx 32rpx;
  }
  
  .avatar-container {
    left: 32rpx;
  }
  
  .company-section,
  .positions-section {
    padding-left: 24rpx;
    padding-right: 24rpx;
  }
}

/* 状态栏适配 */
.header {
  padding-top: calc(60rpx + var(--status-bar-height, 0px));
}

/* 添加过渡动画 */
.user-card,
.company-card,
.view-positions-card,
.position-item,
.signature-container,
.signature-card {
  transition: all 0.3s ease;
}

/* 添加点击反馈效果 */
.company-card:active,
.view-positions-card:active,
.position-item:active {
  opacity: 0.7;
  transform: scale(0.98);
}

/* 状态样式 */
.loading-wrapper,
.empty-state {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 100rpx 0;
}

.loading-text,
.empty-text {
  font-size: 28rpx;
  color: #999999;
}

.load-more,
.no-more {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 40rpx 0;
}

.load-text {
  font-size: 28rpx;
  color: #999999;
}

.no-more-text {
  font-size: 28rpx;
  color: #cccccc;
}

/* 确保底部tabBar不被遮挡 */
.my-home-container {
  padding-bottom: 120rpx;
}
</style>
